from views.base import BaseHandler
import json
from db.datab import db
class ResourceHandler(BaseHandler):
    def get(self):
        #获取参数 所有资源  
        roleid = self.get_query_argument("roleid")
        #所有资源
        sql = "select * from resource where pid>0"
        res = db.findAll(sql)
        data = [{"key":i['id'],'label':i['name']} for i in res]
        #此角色选择的资源
        sql1 = "select resourceid from role_resource where userid=%d"%(int(roleid))
        idlist = db.findAll(sql1)
        checklist = []
        for j in idlist:
            checklist.append(j['resourceid'])

        mes = {"code":200,'reslist':data,'checklist':checklist}
        self.write(mes)

    def post(self):
        sql = "select res.id,res.name,pre.name as pname,pre.id as pid from role_resource as rr left join resource as res on rr.resourceid=res.id inner join resource as pre on res.pid=pre.id where rr.userid=1"
        res = db.findAll(sql)
        list=[]
        idlist=[]
        for i in res:
            if i['pid'] not in idlist:
                idlist.append(i['pid'])
                list.append({"id":i['pid'],"name":i['pname'],"son":[]})

        for j in res:
            for (index,i) in enumerate(list):
                if j['pid']==i['id']:
                    list[index]['son'].append({"id":j['id'],"name":j['name']})

         
        mes={"code":200,"list":list}
        self.write(mes)
